package com.irishud.hud.hardware;

import android.util.Log;

import com.hud.easynavi.SerialPort;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * Created by Administrator on 2017/3/16.
 */
public class SerialPortSendThread extends Thread {
    String TAG = "SerialPortSendThread";
    boolean running = true;
    SerialPort serialPort;
    BlockingDeque<ByteBuffer> queue;

    public SerialPortSendThread(){
        queue = new LinkedBlockingDeque<ByteBuffer>();
    }

    public void openPort(){
        try {
            serialPort = new SerialPort(new File("/dev/ttymxc1"),115200,0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void closePort(){
        if(serialPort!=null){
            serialPort.close();
        }
    }

    public void send(ByteBuffer buffer){
        try {
            queue.put(buffer);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run()
    {
        try {
            while (running && !isInterrupted()) {
                if (queue.size() > 0) Log.d(TAG, "---> queue size:" + queue.size());
                try {
                    ByteBuffer bb = queue.take();
                    if (bb != null) {
                        OutputStream os = serialPort.getOutputStream();
                        os.write(bb.array());
                        Log.d(TAG, "==========> send at serial port");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public void stopRun() {
        running =false;
        closePort();
    }
}

